﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Kjs.Report.Infrastructure;
using Kjs.Report.Domain.Table;
using Microsoft.AspNetCore.Authorization;
using Kjs.Report.JWT;
using AutoMapper;
using Kjs.Report.IService;
using Kjs.Report.Model.Enums;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Kjs.Report.Model;
using Kjs.Report.Business;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Cors;

namespace Kjs.Report.Admin.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [Produces("application/json")]
    [Authorize("Bearer")]
    [EnableCors("Any")]
    [Route("api/user")]
    public class UserController : ApiControllerBase
    {
        private JwtRequirement _requirement;  //自定义策略参数
        private ISysUserService _userService;
        private ISysRoleService _roleService;
        private IMapper _mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        public UserController(ISysUserService userService,  ISysRoleService roleService, JwtRequirement requirement, IMapper mapper)
        {
            _requirement = requirement;
            _userService = userService;
            _roleService = roleService;
            _mapper = mapper;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">请求参数(账号、密码)</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<dynamic> Login([FromBody]LoginRequest request)
         {
            var bllUser = new BLL_SysUser(_userService,  _mapper,  User, Ip);
            var user = await bllUser.Get(request.username);
            if (user == null) throw new BusinessException("登录失败,无效的账号！", ExceptionCode.DataError);

            if (user.password.ToLower() != request.password) throw new BusinessException("账号或密码错误，认证失败！", ExceptionCode.DataError);

            if (!user.isEnable ?? false) throw new BusinessException("登录失败，该账号已被禁用，请与管理员联系！", ExceptionCode.DataInvalid);

            //获取该用户所能管理的组织ID(包含自己)  多个逗号分隔
            if (user.userName.ToLower() != "admin")
            {
                var role = await new BLL_SysRole(_roleService, _userService, _mapper, User, Ip).Get(user.roleId ?? 0);
                if (role == null) throw new BusinessException("该账号没有配置角色,请联系管理员！", ExceptionCode.DataUnsupported);
                user.roleType = role.roleType;
            }
            else
            {
                user.roleType = ERoleType.Admin.ToString();
            }

            //如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
            var claims = new Claim[] {
                new Claim("userId",user.userId.ToString()),
                //new Claim("userNo",user.userNo),
                //new Claim("userName",user.userName),
                //new Claim("realName",user.realName),
                //new Claim("roleId",user.roleId.ToString()),
                //new Claim("email",user.email),
                //new Claim("phone",user.phone),
                //new Claim(ClaimTypes.Name, user.userName),
                //new Claim(ClaimTypes.NameIdentifier, user.userId.ToString()),
                //new Claim(ClaimTypes.Role,user.roleType),
                new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString())
            };
            //用户标识
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaims(claims);

            var token = JwtToken.BuildJwtToken(claims, _requirement);
            return new
            {
                //user,
                token
            };
        }

        /// <summary>
        /// 注销用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("logout")]
        public async Task<bool> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return true;
        }

        /// <summary>
        /// 未授权
        /// </summary>
        [HttpGet("denied")]
        [AllowAnonymous]
        public void Denied()
        {
            throw new BusinessException("您无权限访问该接口", ExceptionCode.DataUnsupported);
        }

    }
}
